import React, {useState} from 'react';
import ProForm, {ProFormText, ProFormTextArea} from '@ant-design/pro-form';
import {Modal, message, TreeSelect, Form, Upload, Image, Button} from 'antd';
import {addCate, editCate, infoCate} from '@/services/cms';
import {UploadOutlined, DeleteOutlined, EyeOutlined} from '@ant-design/icons';

import styles from '../index.less'

const Edit = (props) => {
  const {isModalVisible, isShowModal, actionRef, editId, cateData} = props;
  const [visible, setVisible] = useState(false); // 预览图片
  const [previewImage, setPreviewImage] = useState(''); // 预览图片地址
  const [imageData, setImageData] = useState([]); // 图片数组

  const [formLayout] = useState('horizontal');

  const title = editId === null ? '添加用户' : '编辑用户';

  const formItemLayout =
    formLayout === 'horizontal'
      ? {
        labelCol: {span: 4},
        wrapperCol: {span: 20},
      }
      : null;

  /**
   * 提交按钮
   * @param values
   * @returns {Promise<void>}
   */
  const handleSubmit = async (values) => {
    const data = values;
    // 添加图片
    data.imgs = imageData

    let res = {};
    if (editId === null) {
      res = await addCate(data);
    } else {
      data.category_pid = data.category_pid || 0;
      data.category_id = editId;
      res = await editCate(data);
    }

    if (res.code === 200) {
      message.success(res.msg);
      actionRef.current.reload();
      isShowModal(false);
    }
  };

  /**
   * 作者：糜家智
   * 时间：2022/04/19 17:09:03
   * 功能：获取数据
   */
  const getData = async () => {
    const res = await infoCate({
      category_id: editId,
    })
    res.data.category_pid = res.data.category_pid === 0 ? null : res.data.category_pid
    setImageData([...res.data.imgs])
    return res.data
  };

  /**
   * 作者：糜家智
   * 时间：2022/04/20 15:44:54
   * 功能：递归修改data属性值，配合treeSelect规范数据
   */
  const handleData = (data) => {
    let item = [];
    data.map((list) => {
      let newData = {};
      newData.value = list.category_id;
      newData.title = list.category_name;
      newData.children = list.children ? handleData(list.children) : []; // 如果还有子集，就再次调用自己
      item.push(newData);
    });
    return item;
  };

  /**
   * 作者：糜家智
   * 时间：2022/04/21 14:51:43
   * 功能：移除图片
   */
  function onRemove(index) {
    imageData.splice(index, 1)
    setImageData([...imageData])
  }

  /**
   * 作者：糜家智
   * 时间：2022/04/20 15:45:23
   * 功能：上传图片配置
   */
  const uploadProps = {
    label: '图片',
    name: 'file',
    showUploadList: false,
    action: '/admin/cms.Category/upload',
    accept: '.jpg,.png,.jpeg',
    data: {
      type: 'image',
    },
    headers: {
      AdminToken: localStorage.getItem('access_token') || '',
    },
    beforeUpload(file) {
      if (file.size > 102400 * 5) {
        message.warning('图片不可大于500k~');
        return false;
      }

      if (imageData.length >= 6) {
        message.warning('最多6张图片~');
        return false;
      }

      // message.loading({
      //   content: '图片正在上传中~',
      //   key: 'uploadImg'
      // })
    },
    onChange(info) {
      if (info.file.status === 'done') {
        let res = info.file.response;
        if (res.code === 200) {
          res.data.status = 'done'
          imageData.push(res.data)
          setImageData([...imageData])
          // message.destroy('uploadImg')
          message.success('图片上传成功~')
        } else {
          message.error(res.msg);
        }
      } else if (info.file.status === 'error') {
        message.error('头像上传失败！');
      }
    },
  };

  return (
    <Modal
      title={title}
      visible={isModalVisible}
      onCancel={() => isShowModal(false)}
      footer={null}
      destroyOnClose={true}
    >
      <ProForm
        onFinish={(values) => handleSubmit(values)}
        request={editId == null ? () => {
          return {sort: 50};
        } : () => getData()}
        {...formItemLayout}
        layout={formLayout}
      >
        <Form.Item label="分类父级" name="category_pid">
          <TreeSelect
            style={{width: '100%'}}
            dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
            treeData={handleData(cateData)}
            placeholder="一级父级"
            treeDefaultExpandAll
            allowClear={true}
          />
        </Form.Item>

        <ProFormText
          name="category_name"
          label="分类名称"
          placeholder="请输入分类名称"
          rules={[{required: true, message: '账号不能为空'}]}
        />
        <ProFormText name="title" label="标题" placeholder="请输入标题"/>
        <ProFormText name="keywords" label="关键词" placeholder="请输入关键词"/>
        <ProFormTextArea name="description" label="描述" placeholder="请输入描述"/>

        <Form.Item label="图片">

          <Upload {...uploadProps} >
            <Button icon={<UploadOutlined/>}>点击上传</Button>
            <span className={styles.prompt}>每张图片大小不超过 500 KB，jpg、png格式</span>
          </Upload>

          <div className={styles.preCon}>

            {imageData.map((item, index) => {
              return (
                <div className={styles.preImg} key={item.url}>
                  <img src={item.url}/>
                  {/* 自定义遮罩 */}
                  <div className={styles.preMask}>
                    <EyeOutlined onClick={() => {
                      setVisible(true);
                      setPreviewImage(item.url)
                    }} className={styles.preIcon}/>
                    <DeleteOutlined onClick={() => onRemove(index)} className={styles.preIcon}/>
                  </div>
                </div>
              )
            })}

          </div>

        </Form.Item>

        <ProFormText name="sort" label="排序" placeholder="请输入排序"/>

        <Image
          width={0}
          style={{display: 'none'}}
          preview={{
            visible,
            src: previewImage,
            onVisibleChange: (value) => {
              setVisible(value);
            },
          }}
        />
      </ProForm>

    </Modal>

  );
};

export default Edit;
